package ase.assignment.sts.servlets;

import java.io.PrintWriter;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.ServletContext;
import ase.assignment.sts.utils.ActionConfigReader;
import ase.assignment.sts.utils.ActionConfig;

import ase.assignment.sts.action.GenericAction;

public class MainController extends HttpServlet{

	private final String ACTION_CONFIG_FILE = "ActionConfigFile";
	private final String ACTION_CONFIG_FILE_PATH = "/WEB-INF/actionconfig.xml";

	HashMap actionMap;

	public void init() throws ServletException{
		
		String acf = getInitParameter(ACTION_CONFIG_FILE);
		if( acf == null || acf.equals("") )
			acf = ACTION_CONFIG_FILE_PATH;
		ServletContext sc = getServletContext();
		ActionConfigReader acr = new ActionConfigReader(sc.getRealPath(acf));
		actionMap = acr.parse();

		System.out.println(actionMap.size());

	}

	public void doGet(HttpServletRequest request,
			HttpServletResponse response )
		throws ServletException, IOException {
		doPost( request, response );
	}

	public void doPost(HttpServletRequest request,
			HttpServletResponse response )
		throws ServletException, IOException {
	
		PrintWriter out = response.getWriter();

		String reqURI = request.getRequestURI();
		String reqAction = reqURI.substring(reqURI.lastIndexOf("/")+1, reqURI.lastIndexOf("."));

		out.println(reqAction);

		ActionConfig ac = (ActionConfig)actionMap.get(reqAction);
		if( ac == null )
		{
			out.println("Unexpected action:" + reqAction );
			throw new ServletException("Unexpected action:" + reqAction);
		}
		System.out.println(" doPost : ActionConfig <class> " + ac.getClassName());		
		GenericAction action;

		try{
			Class c = Class.forName(ac.getClassName());
			action = (GenericAction)c.newInstance();

		}catch( Exception e ){
			e.printStackTrace();
			throw new ServletException("can not find action class " + ac.getClassName());
		}

		action.process(request, response );
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Pragma", "no-cache");
		action.forward(request, response, getServletContext() ,ac);


	}
}	
